//
//  UIView+HCTB.m
//  HCToolBox
//
//  Created by Hotacool on 2019/3/19.
//

#import "UIView+HCTB.h"
#import <objc/runtime.h>
#import "NSObject+HCTB.h"

@implementation UIView (HCTB)

hcSynthesizeIdCopyProperty(hctb_hitTestBlock, setHctb_hitTestBlock)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL selectors[] = {
            @selector(hitTest:withEvent:),
        };
        for (NSUInteger index = 0; index < sizeof(selectors) / sizeof(SEL); index++) {
            SEL originalSelector = selectors[index];
            SEL swizzledSelector = NSSelectorFromString([@"hctb_" stringByAppendingString:NSStringFromSelector(originalSelector)]);
            hcSwizzleInstanceMethods([self class], originalSelector, swizzledSelector)
        }
    });
}

- (nullable UIView *)hctb_hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event {
    UIView *originalView = [self hctb_hitTest:point withEvent:event];
    if (self.hctb_hitTestBlock) {
        UIView *view = self.hctb_hitTestBlock(point, event, originalView);
        return view;
    }
    return originalView;
}

#pragma mark - layout
- (CGFloat)width {
    return CGRectGetWidth(self.frame);
}

- (void)setWidth:(CGFloat)width {
    self.frame = hcSetRectWidth(self.frame, width);
}

- (CGFloat)height {
    return CGRectGetHeight(self.frame);
}

- (void)setHeight:(CGFloat)height {
    self.frame = hcSetRectHeight(self.frame, height);
}

- (UIEdgeInsets)hctb_safeAreaInsets {
    if (@available(iOS 11.0, *)) {
        return self.safeAreaInsets;
    }
    return UIEdgeInsetsZero;
}
@end
